package com.cy.pj.ajax.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AjaxController {
    private List<Map<String,String>> list=new ArrayList<>();
    private AjaxController(){
        Map<String,String> map=new HashMap<>();
        map.put("id", "100");
        map.put("city", "Shanghai");
        list.add(map);
        map=new HashMap<>();
        map.put("id", "500");
        map.put("city", "Anhui");
        list.add(map);
    }
    @RequestMapping("/doAjaxPut")
    public String doUpdateobject(@RequestParam Map<String,String> paramMap){
        String id=paramMap.get("id");
        Iterator<Map<String,String>> it=list.iterator();
        while (it.hasNext()){
            Map<String,String>  map=it.next();
            if (map.get("id").equals(id)){
                map.put("city", paramMap.get("city"));
            }
        }
        return "update ok";
    }
    @DeleteMapping("/doAjaxDelete/{id}")
    public String doDeleteObject(@PathVariable String id){
        Iterator<Map<String,String>> it=list.iterator();
        while (it.hasNext()){
            Map<String,String> map=it.next();
            if (map.get("id").equals(id)){
                it.remove();
            }
        }
        return "delete ok";
    }
    @PostMapping ("/doAjaxPost")
    public String doSaveObject(@RequestParam Map<String,String> map){
        list.add(map);
        return "save ok";
    }
    @PostMapping("/doAjaxPostJSON")
    public String doSaveJsonObject(@RequestBody Map<String,String> map){
        list.add(map);
        return "save json ok";
    }
    @RequestMapping(path = {"/doAjaxGet/{city}","/doAjaxGet"})
    public List<Map<String,String>> doAjaxGet(@PathVariable (required = false)String city){
        if(city==null||"".equals(city))return list;
        List<Map<String,String>> listdb=new ArrayList<>();
        for (Map<String,String> s:list) {
            if (s.get("city").contains(city)){
                listdb.add(s);
            }
        }
        return listdb;
    }
    @GetMapping("/doAjaxStart")
    public  String doAjaxStart() throws InterruptedException {
        Thread.sleep(3000);
        return "Response Result of Ajax Request 01";
    }
}
